package com.ktjy.ch15.controller;

import com.ktjy.ch15.entity.SysRole;
import com.ktjy.ch15.entity.SysUser;
import com.ktjy.ch15.service.SysRoleService;
import com.ktjy.ch15.service.SysUserService;
import com.ktjy.ch15.service.UploadService;
import com.ktjy.ch15.utils.Constants;
import com.ktjy.ch15.utils.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

@Controller
@RequestMapping("/main/user")
public class SysUserController extends BaseController{
    private static final Logger LOGGER =
            LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private UploadService uploadService;


    @RequestMapping("/page")
    public String page(Model model, SysUser condition,
                       @RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo,
                       @RequestParam(value = "pageSize", defaultValue = "5") Integer
                               pageSize) {
        Page<SysUser> page = null;
        try {
            // 查询用户的分页信息
            page = sysUserService.findPage(condition, pageNo, pageSize);
            // 查询所有的角色信息
            List<SysRole> roleList = sysRoleService.findAll();
            // 将分页数据、角色列表和查询条件设置到模型数据中
            model.addAttribute("pageInfo", page);
            model.addAttribute("roleList", roleList);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 page 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "user/page";
    }

    @GetMapping("/save")
    public String toSave(Model model) {
        List<SysRole> roleList = null;
        try {
            roleList = sysRoleService.findAll();
            // 有角色下拉框需要数据
            model.addAttribute("roleList", roleList);
            // 回显数据时需要 sysUser，这里给个空对象避免出错
            model.addAttribute("sysUser", new SysUser());
        } catch (Exception e) {
            LOGGER.error("SysUserController中的toSave方法执行发生错误。", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    @PostMapping("/save")
    public String doSave(SysUser sysUser,
                         HttpSession session,
                         HttpServletRequest request,
                         @RequestParam("idPic") MultipartFile idPic,
                         @RequestParam("workPic") MultipartFile workPic) {
        String[] allowImageExt = {"jpg", "jpeg", "png", "gif", "bmp"};
        try {
            // 上传证件照
            String idPicPath = uploadService.uploadFile(idPic, allowImageExt);
            sysUser.setIdPicPath(idPicPath);
// 上传工作照
            String workPicPath = uploadService.uploadFile(workPic, allowImageExt);
            sysUser.setWorkPicPath(workPicPath);

            SysUser loginUser= (SysUser)session.getAttribute(Constants.SESSION_USER);

            boolean ok =false;
            if(sysUser.getId()==null){//新增
                sysUser.setCreatedUserId(loginUser.getId());
                sysUser.setCreatedTime(new Date());
                ok = sysUserService.save(sysUser);
            }else{//修改
                sysUser.setUpdatedUserId(loginUser.getId());
                sysUser.setUpdatedTime(new Date());
                ok=sysUserService.update(sysUser);
            }

            if(ok){
                //跳转到列表;重定向到分页方法
                return redirect("/main/user/page");
            }else{
                //跳回新增页面
                return "user/save";
            }
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 save 方法执行发生错误。{} ",e);
            throw new RuntimeException(e);
        }
    }

//    @GetMapping("/view/{id}")
//    public String view(@PathVariable("id") Long id, Model model){
//        SysUser sysUser = null;
//        try {
//            sysUser = sysUserService.findById(id);
//            model.addAttribute("sysUser", sysUser);
//        } catch (Exception e) {
//            LOGGER.error("SysUserController 中的 view 方法执行发生错误。 ", e);
//            throw new RuntimeException(e);
//        }
//        return "user/view";
//    }

    @GetMapping("/{id}/view")
    @ResponseBody
    public Object view(@PathVariable("id") Long id) {
        Map<String,Object> map = new HashMap<>();

        try {
            SysUser sysUser = sysUserService.findById(id);
            if(sysUser!=null){
                map.put("code",200);
                map.put("data",sysUser);
            }else {
                map.put("code",500);
            }
        }catch (Exception e){
            LOGGER.error("发生错误，{}",e);
            map.put("code",500);
        }
        return map;
    }

    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        SysUser sysUser = null;
        List<SysRole> roleList = null;
        try {
            sysUser = sysUserService.findById(id);
            roleList = sysRoleService.findAll();
            // 有角色下拉框需要数据
            model.addAttribute("roleList", roleList);
            // 回显数据时需要 sysUser，这里给个空对象避免出错
            model.addAttribute("sysUser", sysUser);
        } catch (Exception e) {
            LOGGER.error("SysUserController 中的 toEdit 方法执行发生错误。 ", e);
            throw new RuntimeException(e);
        }
        return "user/save";
    }

    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Object del(@PathVariable("id") Long id) {
        Map<String,Object> map = new HashMap<String,Object>();
        try {
            boolean ok = sysUserService.delete(id);
            if (ok){
                map.put("code",200);
                map.put("msg","删除成功");
            }else {
                map.put("code",500);
                map.put("msg","删除失败");
            }
        }catch (Exception e){
            LOGGER.info("发生错误",e);
            map.put("code",500);
            map.put("msg","发生异常");
        }
        return map;
    }

    @GetMapping("/accountExist")
    @ResponseBody
    public Object accountExist(@RequestParam("account") String account) {
        Map<String,Object> map = new HashMap<>();
        try {
            SysUser sysUser = sysUserService.findByAccount(account);
            if (sysUser != null){
                map.put("exist",1);
            }else {
                map.put("exist",0);
            }
        }catch (Exception e){
            LOGGER.error("SysUserController中的accountExists方法执行发生错误", e);
            map.put("exist",-1);
            map.put("error", "出现异常，请联系管理员处理！ ");
        }
        return map;
    }

    @RequestMapping("/changePwd")
    public String changePwd(){
        return "sys/changePwd";
    }

    @GetMapping("/oldPasswordCheck")
    @ResponseBody
    public Object oldPasswordCheck(@RequestParam("oldPassword") String oldPassword) {
        Map<String,Object> map = new HashMap<>();
        try {
            SysUser sysUser = sysUserService.findByPassword(oldPassword);
            if (sysUser != null){
                map.put("pass",1);
            }else {
                map.put("pass",0);
            }
        }catch (Exception e){
            LOGGER.error("ChangePwdController中的oldPasswordCheck方法执行发生错误", e);
            map.put("exist",-1);
            map.put("error", "出现异常，请联系管理员处理！ ");
        }
        return map;
    }
}
